package org.zachary.agent.infrastructure.service;

import org.springframework.stereotype.Service;
import org.zachary.agent.domain.aggregate_model.token.AccessToken;
import org.zachary.agent.domain.aggregate_model.token.DeviceId;
import org.zachary.agent.domain.aggregate_model.token.RedisTokenEntity;
import org.zachary.agent.domain.aggregate_model.token.RefreshToken;
import org.zachary.agent.domain.repository.TokenRepository;
import org.zachary.agent.domain.service.TokenService;
import org.zachary.agent.infrastructure.exception.TokenValidatorException;
import org.zachary.agent.infrastructure.utils.JwtUtil;

import java.util.HashMap;
import java.util.Map;
import java.util.Optional;

@Service
public class JwtTokenServiceImpl implements TokenService {
    private final TokenRepository tokenRepository; // Redis 仓储

    public JwtTokenServiceImpl(TokenRepository tokenRepository) {
        this.tokenRepository = tokenRepository;
    }
    @Override
    public AccessToken generateAccessToken(String userId) {
        String token = JwtUtil.createAccessToken(userId);
        long expire=3*60*60;
        return new AccessToken(token, expire);
    }
    @Override
    public RefreshToken generateRefreshToken(String userId, DeviceId deviceId) {
        String token = JwtUtil.createRefreshToken(userId, deviceId);
        long expire=7*24*60*60;
        RefreshToken refreshToken = new RefreshToken(token, expire);
        System.out.println(refreshToken.getRefreshExpires());
        return refreshToken;
    }
    @Override
    public Map<String,Object> rotateRefreshToken(String refreshToken, String userId, DeviceId deviceId) throws Exception {
        Optional<RedisTokenEntity> storedToken = tokenRepository.findByUserIdAndDeviceId(userId, deviceId);
        if (storedToken.isEmpty() || !storedToken.get().getToken().equals(refreshToken)) {
            throw new TokenValidatorException("Refresh token invalid");
        }
        AccessToken access=generateAccessToken(userId);
        RefreshToken refresh=generateRefreshToken(userId,deviceId);
        Map<String,Object> map=new HashMap<>();
        map.put("refresh",refresh);
        map.put("access",access);
        return map;
    }

    @Override
    public boolean validateRefreshToken(String token) throws Exception {
        return JwtUtil.validateToken(token);
    }
}
